String.prototype.hashCode = function(){
    var hash = 0, i, char;
    if (this.length == 0) return hash;
    for (i = 0; i < this.length; i++) {
        char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};


function get_full_name(node) {
	//get items until root
	var nodes = [];
	var current = node;
	
	while ('__root' != current.attr('id') && current.parent())
	{
		if(current.attr('id') && current.prop("tagName") == 'LI')
			nodes.push(current.text().split("\n")[0]);
		current = current.parent();
	}
	
	
	return '/'+nodes.reverse().join('/');
}

function json_to_ul(id,data) {
	var ret = (id=='__root') ? '<ul id="__root">' : '';
	
	if (data && data instanceof Object && !(data instanceof Array)) 
	{
		id =  data.title;
		
		if(id.match(/\//))
		{
			id = id.split(/\//);
			id = id[id.length-1];
		}
		ret += '<li id="li_{1}" class="folder">{0}\n<ul id="{1}">'.format(id,id.hashCode());
		ret += json_to_ul(null,data.data );
		$.each(data.children, function(idx,page_title) {
			ret += '<li class="file jl" eip-controller="{2}" id="page_{0}">{1}</li>'.format(page_title.hashCode(), page_title, data.title); 
		});
		ret += '\n</ul></li>';
	} 
	else if (data && data instanceof Array) {
		$.each(data, function(key, val) {
			ret += json_to_ul(key,val);
		});
	}

	return (id=='__root') ? ret + '</ul>' : ret;
}


var spta_enabled = true;
//toggle static page toolbar actions - add,delete,move
function toggle_spta() {
	$.each($('#static_page_toolbar').children('.icon_32_add, .icon_32_delete, .icon_32_move, .icon_32_edit'), function(k,v) {
		 if(spta_enabled)
		 	$(v).attr('disabled', 'disabled'); //addClass('disabled')
		 else
		 	$(v).removeAttr('disabled'); //.removeClass('dsiabled');
	});
	
	spta_enabled=!spta_enabled;
}

$(document).ready(function() {
	var expanded=false;
	var editor=null;
	
	toggle_spta();
	$.getJSON( eip_base_url + '/EIP/Ide/Static_Page/get_static_pages_json', function(data) {
  		$('#static_pages').html( json_to_ul('__root', data) );
  		expanded=true;
 	});
 	//click on a static_page link
 	$('#static_pages').on('click', '.file', function(evt) {
 		if(editor)
 		{
 			editor.destroy();
 			editor=null;
 		}
 		$('.file').removeClass('selected');
 		$(this).addClass('selected');
 		
 		$('#preview_pane').load( get_full_name($(this)) );
 		toggle_spta();
 		evt.stopPropagation();
 	});
 	//collospe folders
 	$('#static_pages').on('click', '.folder', function(evt) {
 		$(this).children('ul').toggle();
 		evt.stopPropagation();
 	});
 	
 	//toolbar functions
 	//expand
 	$('#static_page_toolbar .icon_32_expand').click( function() {
 		$.each( $('#static_pages .folder'), function(k,v) {
 			if(expanded)
 				$(v).children('ul').hide();
 			else
 				$(v).children('ul').show();
 		});
 		expanded=!expanded;
 	});
 	//add
 	$('#static_page_toolbar .icon_32_add[disabled!="disabled"]').click( function() {
 		console.log($(this).text());
 	});
 	
 	
 	
 	$('body').on('dblclick', '#preview_pane', function(evt) {
 		if(editor)
 		{
 			return;
 		}
 		
 		
 		var html = $(this).html();
 		
 		var edit_form = '<form id="dynamic_edit" class="edit_form" method="post" action="' + eip_base_url + 'EIP/Ide/Static_Page/edit?controller={0}&action={1}"><text area id="static_page">{2}</textarea></form>'.format(
 				encodeURIComponent($('.selected').attr('eip-controller')),
 				encodeURIComponent($('.selected').text()),
 				html);

 		$(this).html(edit_form);
 		
 		var config = {
			customConfig :eip_base_url + 'resources/js/ckeditor/config.js',
			fullPage:true,
			extraPlugins : 'docprops',
			baseHref : "http://{$smarty.server.HTTP_HOST}",
			skin: 'kama,' + eip_base_url + 'resources/js/ckeditor/skins/kama'
		};
 		
 		editor = CKEDITOR.replace('static_page',config);
 		
 		editor.on( 'saveSnapshot', function(e) {
 			$('.cke_button_save').removeClass('cke_disabled');
 		});
 		evt.stopPropagation();
 	})
 	$('#preview_pane').on('click','.cke_button_save', function (e) {
 		var d='#dynamic_edit';
 		$('#static_page').val( editor.getData() );
 		
 		var dataString = "static_page="+$('#static_page').val();
			$.ajax({  
	 		 type: $(d).attr('method'),
	 		 url: $(d).attr('action'),
	 		 data: dataString
			});
			
		var html = $('#static_page').val();
		editor.destroy();
		editor = null;
		$('#preview_pane').html(html);
		return false;
		
 	});

 	 	
});
